using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Terra.Core.Common.ApiResponse;
using Terra.Core.Common.Models.Common;
using Terra.Core.Common.Models.Pagination;
using Terra.Data.Models.Identity;
using Terra.Service.Identity.Interfaces;

namespace Terra.WebApi.Areas.Admin.Controllers;

/// <summary>
/// 菜单管理控制器
/// </summary>
/// <remarks>
/// 提供以下功能：
/// <list type="bullet">
/// <item><description>菜单查询</description></item>
/// <item><description>菜单详情</description></item>
/// <item><description>菜单树形结构</description></item>
/// <item><description>菜单选择列表</description></item>
/// <item><description>菜单创建</description></item>
/// <item><description>菜单更新</description></item>
/// <item><description>菜单删除</description></item>
/// <item><description>批量删除菜单</description></item>
/// <item><description>前端路由菜单</description></item>
/// </list>
/// </remarks>
[Area("Admin")]
[ApiController]
[Route("api/admin/menus")]
[ApiExplorerSettings(GroupName = "v1-admin")]
[Authorize]
public class MenuController : ControllerBase
{
    private readonly IMenuService _menuService;
    private readonly ILogger<MenuController> _logger;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="menuService">菜单服务</param>
    /// <param name="logger">日志记录器</param>
    public MenuController(
        IMenuService menuService,
        ILogger<MenuController> logger)
    {
        _menuService = menuService ?? throw new ArgumentNullException(nameof(menuService));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    #region 查询接口

    /// <summary>
    /// 分页获取菜单列表
    /// </summary>
    /// <param name="query">查询条件</param>
    /// <returns>菜单分页列表</returns>
    [HttpGet]
    [ProducesResponseType(typeof(ApiResponse<PagedList<MenuItemDto>>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> GetPagedMenus([FromQuery] MenuQueryDto query)
    {
        var response = await _menuService.GetPagedMenusAsync(query);
        return Ok(response);
    }

    /// <summary>
    /// 获取菜单详细信息
    /// </summary>
    /// <param name="id">菜单ID</param>
    /// <returns>菜单详细信息</returns>
    [HttpGet("{id}")]
    [ProducesResponseType(typeof(ApiResponse<MenuDetailDto>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 404)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> GetMenuById(Guid id)
    {
        var response = await _menuService.GetMenuByIdAsync(id);
        return response.IsSuccess ? Ok(response) : BadRequest(response);
    }

    /// <summary>
    /// 获取菜单树形结构
    /// </summary>
    /// <returns>菜单树形结构</returns>
    [HttpGet("tree")]
    [ProducesResponseType(typeof(ApiResponse<List<MenuTreeDto>>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> GetMenuTree()
    {
        var response = await _menuService.GetMenuTreeAsync();
        return Ok(response);
    }

    /// <summary>
    /// 获取菜单选择列表
    /// </summary>
    /// <returns>菜单选择列表</returns>
    [HttpGet("select")]
    [ProducesResponseType(typeof(ApiResponse<List<MenuSelectDto>>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> GetMenuSelectList()
    {
        var response = await _menuService.GetMenuSelectListAsync();
        return Ok(response);
    }

    /// <summary>
    /// 获取前端路由菜单树
    /// </summary>
    /// <returns>前端路由菜单树</returns>
    [HttpGet("router")]
    [ProducesResponseType(typeof(ApiResponse<List<RouterMenuDto>>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> GetRouterMenuTree()
    {
        var response = await _menuService.GetRouterMenuTreeAsync();
        return Ok(response);
    }

    #endregion

    #region 操作接口

    /// <summary>
    /// 创建菜单
    /// </summary>
    /// <param name="dto">创建菜单信息</param>
    /// <returns>创建结果</returns>
    [HttpPost]
    [ProducesResponseType(typeof(ApiResponse<Guid>), 201)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> CreateMenu([FromBody] MenuCreateDto dto)
    {
        var response = await _menuService.CreateMenuAsync(dto);

        if (!response.IsSuccess)
        {
            // 根据错误码返回不同的HTTP状态
            return BadRequest(response);
        }

        return Created($"/api/admin/menus/{response.Data}", response);
    }

    /// <summary>
    /// 更新菜单
    /// </summary>
    /// <param name="id">菜单ID</param>
    /// <param name="dto">更新菜单信息</param>
    /// <returns>更新结果</returns>
    [HttpPut("{id}")]
    [ProducesResponseType(typeof(ApiResponse), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> UpdateMenu(Guid id, [FromBody] MenuUpdateDto dto)
    {
        var response = await _menuService.UpdateMenuAsync(id, dto);

        if (!response.IsSuccess)
        {
            return BadRequest(response);
        }

        return Ok(response);
    }

    /// <summary>
    /// 删除菜单
    /// </summary>
    /// <param name="id">菜单ID</param>
    /// <returns>删除结果</returns>
    [HttpDelete("{id}")]
    [ProducesResponseType(typeof(ApiResponse), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> DeleteMenu(Guid id)
    {
        var response = await _menuService.DeleteMenuAsync(id);

        if (!response.IsSuccess)
        {
            return BadRequest(response);
        }

        return Ok(response);
    }

    /// <summary>
    /// 批量删除菜单
    /// </summary>
    /// <param name="dto">批量删除参数</param>
    /// <returns>批量删除结果</returns>
    [HttpPost("batch-delete")]
    [ProducesResponseType(typeof(ApiResponse<BatchOperationResult>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    [ProducesResponseType(typeof(ApiResponse), 401)]
    public async Task<IActionResult> BatchDeleteMenus([FromBody] BatchDeleteDto<Guid> dto)
    {
        if (dto == null || dto.Ids == null || dto.Ids.Count == 0)
        {
            return BadRequest(ApiResponse.Error("VAL001", "请选择需要删除的菜单"));
        }

        var response = await _menuService.BatchDeleteMenusAsync(dto);

        if (!response.IsSuccess)
        {
            return BadRequest(response);
        }

        // 即使部分失败也返回200，结果中包含详细信息
        return Ok(response);
    }

    #endregion
}